import common from "./BQGIS-modelTool"
/**
 * 材质面
 * @param    viewer  Mars3d实例对象
 * @returns 
 */
export function initBQGIS_polygon(viewer = window.viewer){
    return new BQGIS_polygon(viewer)
}
export function BQGIS_polygon(viewer = window.viewer){
    this.viewer = viewer
    // 创建矢量数据图层
    this.graphicLayer = new mars3d.layer.GraphicLayer()
    this.viewer.addLayer(this.graphicLayer)
    this.common =new common()
    this.domList={}
    this.hls = {}
}
/**
 * 添加材质
 * @param  type             材质类型（必传）（对象.type 默认颜色）
 * @param  name             名称（可不传入）
 * @param  id               id（可不传入）       
 * @param  isSave           是否保存到数据库（可不传入）（默认 false）
 * @param  color            颜色（可不传入）（默认#29cf34 ）
 * @param  opacity          透明度（可不传入）（范围0-1 默认1 只对颜色材质有效）
 * @param  url              视频或图片地址（视频或图片类型必传）
 * @returns 
 */
BQGIS_polygon.prototype.addPolygon=function(option={}){
    let param = Object.assign({
        id:this.common.guid(),
        name:'材质面',
        type:'color',
        isSave:false,
        color:'#29cf34',
        opacity:1,
        url:'',
        isSynchronize:false,    
        positions:[]
    },option)
    let graphic = new mars3d.graphic.PolygonEntity({
        styleType:param.type,
        id:param.id,
        name:param.name,
        positions:param.positions,
        style:this.getStyle(param)
    })
    this.graphicLayer.addGraphic(graphic) 
    if(param.isSave){
        this.common.saveSymbolAttribute({id:param.id, type:'polygon',typeName:'面材质',attribute:JSON.stringify(param)},true)
    }
    return param.id
}
/**
 * 添加材质
 * @param  type             材质类型（必传）（对象.type 默认颜色）
 * @param  name             名称（可不传入）
 * @param  id               id（可不传入）       
 * @param  isSave           是否保存到数据库（可不传入）（默认 false）
 * @param  color            颜色（可不传入）（默认#29cf34 ）
 * @param  opacity          透明度（可不传入）（范围0-1 默认1 只对颜色材质有效）
 * @param  url              视频或图片地址（视频或图片类型必传）
 * @returns 
 */
BQGIS_polygon.prototype.updatePolygon=function(option={}){
    let data= this.graphicLayer.getGraphicById(option.id)
    let param = Object.assign({
        id:option.id,
        name:'材质面',
        type:'color',
        isSave:false,
        color:'#29cf34',
        opacity:1,
        url:'',
        isSynchronize:false,    
      
    },option)
    if(data){
        this.removeVideoElement(option.id)
        let temp= this.getStyle(param)
        data.setStyle(temp)
        if(option.isSave){
            this.common.saveSymbolAttribute({id:data.id, type:'polygon',typeName:'多边形材质',attribute:JSON.stringify(param)},false)                    
        }
        
    }
}
/**
 * 根据id清除图层
 */
BQGIS_polygon.prototype.removePolygon=function(id){
    let data= this.graphicLayer.getGraphicById(id)
    if(data){
        this.graphicLayer.removeGraphic(data)
    }
}
/**
 * 清除所有图层
 */
BQGIS_polygon.prototype.clearPolygon=function(){
    this.graphicLayer.clear()
}
/**
 * 添加材质
 * @param  type             材质类型（必传）（对象.type 默认颜色）
 * @param  name             名称（可不传入）
 * @param  id               id（可不传入）       
 * @param  isSave           是否保存到数据库（可不传入）（默认 false）
 * @param  color            颜色（可不传入）（默认#29cf34 ）
 * @param  opacity          透明度（可不传入）（范围0-1 默认1 只对颜色材质有效）
 * @param  url              视频或图片地址（视频或图片类型必传）
 * @returns 
 */
BQGIS_polygon.prototype.draw=function(option={}){
    let param = Object.assign({
        id:this.common.guid(),
        name:'材质面',
        type:'color',
        isSave:false,
        color:'#29cf34',
        opacity:1,
        url:'',
        isSynchronize:false,    
      
    },option)
    this.graphicLayer.startDraw({
        id:param.id,
        name:param.name,
        type:'polygon',
        styleType:param.type,
        style:this.getStyle(param),
        success:graphic=>{
            if(param.isSave){
                param.positions = this.getPosition(graphic.points)
                this.common.saveSymbolAttribute({id:param.id, type:'polygon',typeName:'材质面',attribute:JSON.stringify(param)},true)
            }
        }
    })
    return param.id

}
BQGIS_polygon.prototype.getPosition=function(points){
    let ret=[]
    points.forEach(data => {
        ret.push([data.lng,data.lat,data.alt])
    })
    return ret
}
BQGIS_polygon.prototype.getStyle=function(param){
    let ret;
    switch (param.type) {
        case 'color':
            ret={
                id:param.id,
                name:param.name,                
                color:param.color,
                opacity:param.opacity
            }
            break;
        case 'video':
            let videoElement = this.createVideoElement(param.id)
            this.setVideoSrc({
                src: param.url,
                isSynchronize: param.isSynchronize,
                videoElement
            })
            ret = {
                id:param.id,
                name:param.name,                
                material:videoElement,
            }
            break;
        case 'image':
            ret={
                id:param.id,
                name:param.name,                
                material:param.url,
            }
            break;
        default:
            break;
    }
    return ret
}
BQGIS_polygon.prototype.type={
    颜色:"color",
    视频:"video",
    图片:"image"
}
BQGIS_polygon.prototype.createVideoElement = function (id){
    if(id in this.domList){
        return
        // return this.domList[id].dom
    }
    const videoElement = mars3d.DomUtil.create("video", "", document.body)
    if(id){
        videoElement.setAttribute("id", id)
    }
    videoElement.setAttribute("muted", "muted")
    videoElement.setAttribute("autoplay", "autoplay")
    videoElement.setAttribute("loop", "loop")
    videoElement.setAttribute("crossorigin", "")
    videoElement.setAttribute("controls", "")
    videoElement.style.display = "none"
    this.domList[id] =  {
        dom: videoElement,
        state: 'stop'
    }
    return videoElement
}
BQGIS_polygon.prototype.removeVideoElement = function (id) {
    this.removeDom(id)
    this.removeHis(id)
}
BQGIS_polygon.prototype.removeHis = function (id) {
    if(id in this.hls){
        this.hls[id].destroy()
        delete this.hls[id]
    }
}
BQGIS_polygon.prototype.removeDom = function (id) {
    if(id in this.domList) {
        document.body.removeChild(this.domList[id].dom)
        this.domList[id].dom.remove()
        this.domList[id].dom = null
        delete this.domList[id]
    }
}
BQGIS_polygon.prototype.setVideoSrc = function ({src, isSynchronize, videoElement}) {
    const id = videoElement.id
    if(id in this.domList && this.domList[id].state === 'play') return // 已经播放，则不进行设置
    if (/\.(mp4)$/.test(src)) {
        videoElement.setAttribute("src", src)
        this.setDomState(id, 'mp4')
    } else if (/\.(flv)$/.test(src)) {
        this.setFlvVideo(videoElement, src)
        this.setDomState(id, 'flv')
    } else if (/\.(m3u8)$/.test(src)) {
        this.hls[id] = this.setHLSVideo(videoElement, src)
        this.setDomState(id, 'hls')
    }
    if(isSynchronize){
        new Cesium.VideoSynchronizer({
            clock: viewer.clock,
            element: videoElement,
        });
    }
    return videoElement
}
BQGIS_polygon.prototype.setDomState = function (id ,type) {
    if(id in this.domList) {
        this.domList[id].type = type
        this.domList[id].state = 'play'
    }
}
BQGIS_polygon.prototype.setFlvVideo = function (videoElement, flvUrl) {
    if (window.flvjs.isSupported()) {
        const flvPlayer = window.flvjs.createPlayer({
            type: "flv",
            url: flvUrl
        })
        flvPlayer.attachMediaElement(videoElement)
        flvPlayer.load()
        flvPlayer.play()
    } else {
        console.log("不支持flv格式视频")
    }
    return videoElement
}
BQGIS_polygon.prototype.setHLSVideo = function (videoElement, hlsUrl) {
    if (window.Hls.isSupported()) {
        const hls = new window.Hls()
        hls.attachMedia(videoElement)
        hls.on(Hls.Events.MEDIA_ATTACHED, function () {
            hls.loadSource(hlsUrl)
            hls.on(window.Hls.Events.MANIFEST_PARSED, function () {
                videoElement.play()
            })
        })
        return hls
    } else if (videoElement.canPlayType("application/vnd.apple.mpegurl")) {
        videoElement.src = hlsUrl
        videoElement.addEventListener("loadedmetadata", function () {
            videoElement.play()
        })
        return
    }
}